import React, { Component, PropTypes } from 'react';
import { StyleSheet, View, Text, PanResponder } from 'react-native';

var UIManager = require('NativeModules').UIManager;

var noop = () => {};
var returnTrue = () => true;

/**
 * A-Z
 * 实现逻辑：
 *  使用PanResponder 计算坐标，获取section index。
 *  由于 onPanResponderGrant事件 y0 很多时候为0（不知道为什么），所以点击事件用View自己的onResponderGrant事件
 */
class SectionList extends Component {

  constructor(props, context) {
    super(props, context);

    this.onSectionSelect = this.onSectionSelect.bind(this);
    this.resetSection = this.resetSection.bind(this);
    this.detectAndScrollToSection = this.detectAndScrollToSection.bind(this);
    this.lastSelectedIndex = null;
  }

  onSectionSelect(sectionId, fromTouch) {
    this.props.onSectionSelect && this.props.onSectionSelect(sectionId);

    if (!fromTouch) {
      this.lastSelectedIndex = null;
    }
  }

  resetSection() {
    this.lastSelectedIndex = null;
  }

  componentWillMount() {
    this._panResponder = PanResponder.create({
      // 要求成为响应者：
      onStartShouldSetPanResponder: () => false,
      onMoveShouldSetPanResponder: () => true,
      onPanResponderGrant: (evt, gestureState) => { // 由于 y0 很多时候为0（不知道为什么），所有用View的onResponderGrant事件
        // this.tapTimeout = setTimeout(() => {
        //   this.detectAndScrollToSection(gestureState.y0); // 当响应器产生时的屏幕坐标
        // }, 100);
      },
      onPanResponderMove: (evt, gestureState) => {
        // clearTimeout(this.tapTimeout);
        this.detectAndScrollToSection(gestureState.moveY); // 最近一次移动时的屏幕纵坐标
      },
      onPanResponderRelease: () => {
        this.resetSection();
      },
      onPanResponderTerminate: () => {
        this.resetSection();
      }
    });
  }

  detectAndScrollToSection(y) {
    let top = y - (this.absContainerTop || 0);
    let index = 0;
    if (top >= 1 && top <= this.containerHeight) {
      // index = Math.round((top / this.containerHeight) * this.props.sections.length); // 获取索引
      index = parseInt((top / this.containerHeight) * this.props.sections.length); // 获取索引
    }
    if (this.lastSelectedIndex !== index) {
      this.lastSelectedIndex = index;
      this.onSectionSelect(this.props.sections[index], true);
    }

    // UIManager.measureViewsInRect(rect, e.target, noop, (frames) => {
    //   if (frames.length) {
    //     var index = frames[0].index;
    //     if (this.lastSelectedIndex !== index) {
    //       this.lastSelectedIndex = index;
    //       this.onSectionSelect(this.props.sections[index], true);
    //     }
    //   }
    // });
  }

  onResponderGrant(e) {
    let y = e.nativeEvent.pageY;
    this.detectAndScrollToSection(y);
  }

  _onLayout() {
    this.refs.alphabetContainer.measure((x1, y1, width, height, px, py) => {
      this.absContainerTop = py;
      this.containerHeight = height;
    });
  }

  render() {
    var SectionComponent = this.props.component;
    var sections = this.props.sections.map((section, index) => {
      var title = this.props.getSectionListTitle ?
        this.props.getSectionListTitle(section) :
        section;

      var child = SectionComponent ?
        <SectionComponent
          sectionId={section}
          title={title}
        /> :
        <View
          style={styles.item}>
          <Text style={[styles.text]}>{title}</Text>
        </View>;

      return (
        <View key={index} pointerEvents="none">
          {child}
        </View>
      );
    });

    //  onStartShouldSetResponder={returnTrue}
    //       onMoveShouldSetResponder={returnTrue}
    //       onResponderGrant={this.detectAndScrollToSection}
    //       onResponderMove={this.detectAndScrollToSection}
    //       onResponderRelease={this.resetSection}
    return (
      <View
        style={[styles.container]}
      >
        <View
          ref="alphabetContainer"
          onLayout={this._onLayout.bind(this)}
          style={this.props.style}
          {...this._panResponder.panHandlers}
          onStartShouldSetResponder={returnTrue}
          onResponderGrant={this.onResponderGrant.bind(this)}
        >
          {sections}
        </View>
      </View>
    );
  }
}

SectionList.propTypes = {

  /**
   * A component to render for each section item
   */
  component: PropTypes.func,

  /**
   * Function to provide a title the section list items.
   */
  getSectionListTitle: PropTypes.func,

  /**
   * Function to be called upon selecting a section list item
   */
  onSectionSelect: PropTypes.func,

  /**
   * The sections to render
   */
  sections: PropTypes.array.isRequired,

  /**
   * A style to apply to the section list container
   */
  style: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.object,
  ])
};

var styles = StyleSheet.create({
  container: {
    position: 'absolute',
    backgroundColor: 'transparent',
    alignItems:'center',
    justifyContent:'center',
    right: 0,
    top: 0,
    bottom: 0
  },

  item: {
    padding: 0
  },

  text: {
    fontWeight: '700',
    color: '#008fff'
  }
});

module.exports = SectionList;
